<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.username"
            clearable
            placeholder="请输入账号"
            :prefixIcon="IconSearch"
            style="width: 230px"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.realname"
            clearable
            placeholder="请输入姓名"
            :prefixIcon="IconSearch"
            style="width: 230px"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.status"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="[
              { label: '全部', value: '' },
              { label: '正常', value: 0 },
              { label: '冻结', value: 1 },
            ]"
            placeholder="请选择状态"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <base-input-search
            v-model="filterData.phone"
            clearable
            placeholder="请输入电话"
            :prefixIcon="IconSearch"
            style="width: 230px"
            @submit="getAxiosData(true)"
          ></base-input-search>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconSolarAddCircleLinear" @click="handleAdd()">新增</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="头像" prop="dramaTitle" minWidth="68">
        <template #default="{ row }">
          <base-image style="width: 40px; height: 40px; border-radius: 60%" :src="row.avatar || avatarUrl"></base-image>
        </template>
      </el-table-column>
      <el-table-column fixed prop="username" label="账号" width="180"></el-table-column>
      <el-table-column fixed label="角色" prop="roleName" width="120"></el-table-column>
      <el-table-column label="真实姓名" prop="realname" width="120"></el-table-column>
      <el-table-column label="电话" prop="phone" minWidth="180"></el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        minWidth="90"
        :formatter="(row: _AdminUser) => (row.sex === 1 ? '男' : row.sex === 2 ? '女' : '未知')"
      ></el-table-column>
      <el-table-column label="部门" prop="deptId" minWidth="120">
        <template #default="{ row }">
          {{ deptList.find((v) => v.deptId === row.deptId)?.deptName || '' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" minWidth="120"></el-table-column>
      <el-table-column label="状态" fixed="right" width="90" align="center" headerAlign="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :disabled="row.admin"
            style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)"
            inlinePrompt
            activeText="已启用"
            inactiveText="已冻结"
            :activeValue="0"
            :inactiveValue="1"
            :loading="row._statusLoading"
            :beforeChange="() => handleSetStateSingle(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140" align="center" headerAlign="center">
        <template #default="{ row }">
          <el-button v-if="!row.admin" link type="danger" size="small" :icon="IconDelete" @click="handleDel([row])">删除</el-button>
          <el-button link type="primary" size="small" :icon="IconEdit" @click="openEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <admin-user-info ref="adminUserInfoRef"></admin-user-info>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconDelete from '~icons/ep/delete';
  import IconEdit from '~icons/ep/edit';
  import IconSolarAddCircleLinear from '~icons/solar/add-circle-linear';
  import {
    type AdminUser,
    type AdminUserListRequest,
    type DeptItem,
    changeStatusAdminUserAxios,
    delAdminUserAxios,
    getAdminUserListAxios,
    getSysDeptListAxios,
  } from '@/api/permission-management';
  import AdminUserInfo from './components/admin-user-info.vue';
  import avatarUrl from '@/assets/images/account/avatar.svg';
  const userStore = useUserStore();

  type _AdminUser = AdminUser & {
    /** 修改冻结状态的加载状态 */
    _statusLoading?: boolean;
  };

  const adminUserInfoRef: $RefComp<typeof AdminUserInfo> = ref(null);
  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    type: 'add' as 'add' | 'edit',
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData: Ref<AdminUserListRequest> = ref<AdminUserListRequest>({
    status: '',
    phone: '',
    realname: '',
    username: '',
    current: 1,
    size: 40,
    deptId: userStore.userInfo?.deptId,
  });

  const deptList = ref<DeptItem[]>([]);
  const tableData: Ref<_AdminUser[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    getAxiosData();
  });
  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getAdminUserListAxios(filterData.value);
      const { data } = await getSysDeptListAxios({});
      deptList.value = data;
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 编辑 */
  function openEdit(adminUser: AdminUser) {
    adminUserInfoRef.value?.show({
      type: 'edit',
      adminUser,
      editCallBack: () => {
        getAxiosData(false);
      },
    });
  }

  /** 跳转到新增视频页面 */
  function handleAdd() {
    adminUserInfoRef.value?.show({
      type: 'add',
      addCallBack: () => {
        getAxiosData(false);
      },
    });
  }

  /** 删除 */
  function handleDel(row: _AdminUser[]) {
    if (row.length > 0) {
      ElMessageBox.confirm('删除后不可恢复，您确定删除吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            const ids = row.map((item) => item.userId);
            try {
              await delAdminUserAxios(ids);
              await getAxiosData(false);
              instance.confirmButtonLoading = false;
              done();
              ElToast.success('删除成功');
            } catch (error) {
              instance.confirmButtonLoading = false;
              ElToast.error(error.msg || '删除失败，-BD004');
            }
          } else {
            done();
          }
        },
      });
    } else {
      ElToast.warning('请选择需要删除的用户');
    }
  }

  /** 修改单个解冻状态 */
  async function handleSetStateSingle(row: _AdminUser): Promise<boolean> {
    const name = row.status === 0 ? '冻结' : '启用';
    try {
      row._statusLoading = true;
      await changeStatusAdminUserAxios(row.userId);
      row._statusLoading = false;
      ElToast.success(`${name}成功`);
      return Promise.resolve(true);
    } catch (error) {
      row._statusLoading = false;
      ElToast.error(error.msg || `${name}失败，-BD004`);
      return Promise.reject(false);
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }
</style>
